<template>
  <div class="ImageList-container">
    <a-radio-group v-model="value" :disabled="disabled">
      <div v-for="item in fileList" :key="item.fileId" class="img-wrapper">
        <div class="radio-box">
          <a-radio :value="item.commonId" />
        </div>
        <div class="img-box" @click="handlePreview(item)">
          <a-icon v-if="!disabled" class="close-icon base-btn" type="close" @click.stop="handleRemove(item)" />
          <img :src="getImgUrl(item.fileId, item.commonId)" alt="" />
        </div>
      </div>
    </a-radio-group>
    <!-- 图片预览 -->
    <pre-view :preview-image="previewImage" :visible.sync="previewVisible" :is-download="false" />
  </div>
</template>

<script>
import PreView from '@/components/PreView' // 图片预览
import Vue from 'vue'

export default {
  name: 'ImageList',
  components: {
    PreView
  },
  props: {
    fileList: {
      type: Array,
      default() {
        return []
      }
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      previewImage: '',
      previewVisible: false,
      value: '', // 选中的主图commonId
      token: Vue.getAcloudProvider().getAccessToken()
    }
  },
  watch: {
    fileList: {
      immediate: true,
      deep: true,
      handler(list) {
        if (!list.length) {
          this.value = ''
        }
        list.forEach((item) => {
          if (item.main) {
            this.value = item.commonId
          }
        })
      }
    }
  },
  methods: {
    /**
     * @description: 获取预览地址
     * @param {String} fileId：图片id
     * @param {String} commonId：本地文件服务id
     * @return {String}
     */
    getImgUrl(fileId, commonId) {
      // 本地文件服务id存在则使用本地链接
      return commonId
        ? '/api/ycloud-file-center/oper/download?access_token=' + this.token + '&fileId=' + fileId
        : fileId
    },
    /**
     * 预览
     */
    handlePreview(data) {
      this.previewImage = this.getImgUrl(data.fileId, data.commonId)
      this.previewVisible = true
    },
    /**
     * 删除
     */
    handleRemove(data) {
      this.$emit('remove', { ...data })
    },
    /**
     * 获取选中值
     */
    getValue() {
      return this.value
    }
  }
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.ImageList-container {
  .img-wrapper {
    display: inline-block;
    margin-right: 50px;
    .radio-box {
      display: flex;
      justify-content: center;
      padding-bottom: 10px;
      @{deep} .ant-radio-wrapper {
        margin-right: 0;
      }
    }
    .img-box {
      position: relative;
      cursor: pointer;
      border-radius: 4px;
      overflow: hidden;
      border: 1px dashed #cccccc;
      width: 90px;
      height: 65px;
      .close-icon {
        position: absolute;
        top: 0;
        right: 0;
      }
      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }
  }
}
</style>